package com.pine.app.module.security.oauth.plugin;

import com.pine.app.module.security.core.matcher.RequestMatcher;
import com.pine.app.module.security.core.common.enums.ResponseProduceType;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author xiaoyuan
 * @create 2020/3/6 23:13
 **/

public abstract class AbstractProcessPlugin implements ProcessPlugin {

    private boolean enabled = false;

    private RequestMatcher requestMatcher;

    private String pluginCode;

    private ResponseProduceType responseProduceTypeEnum;

    public AbstractProcessPlugin() {
        init();
    }

    public void init() {

    }

    public void prepare(HttpServletRequest request, HttpServletResponse response, Object o) throws ServletException, IOException {

    }

    public void complete(HttpServletRequest request, HttpServletResponse response, Object o) {

    }


    public void exception(HttpServletRequest request, HttpServletResponse response, Exception e) throws ServletException, IOException {

    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public RequestMatcher getRequestMatcher() {
        return requestMatcher;
    }

    public void setRequestMatcher(RequestMatcher requestMatcher) {
        this.requestMatcher = requestMatcher;
    }

    public String getPluginCode() {
        return pluginCode;
    }

    public void setPluginCode(String pluginCode) {
        this.pluginCode = pluginCode;
    }

    public ResponseProduceType getResponseProduceTypeEnum() {
        return responseProduceTypeEnum;
    }

    public void setResponseProduceTypeEnum(ResponseProduceType responseProduceTypeEnum) {
        this.responseProduceTypeEnum = responseProduceTypeEnum;
    }

    protected boolean matcher(String code, Plugin plugin) {
        if (StringUtils.isBlank(code) || plugin.value() == null || plugin.value().length == 0) {
            return false;
        }
        setPluginCode(code);
        setResponseProduceTypeEnum(plugin.responseType());
        List<String> codes = Arrays.asList(plugin.value());
        return codes.contains(code);
    }
}
